<template>
  <div class="vue-router-demo">
    <h2>Vue Router 路由管理</h2>
    
    <!-- 介绍部分 -->
    <div class="introduction">
      <p>Vue Router 是 Vue.js 官方的路由管理器，用于构建单页面应用(SPA)。</p>
    </div>

    <!-- 1. 基础路由演示 -->
    <section class="demo-section">
      <h3>1. 基础路由演示</h3>
      <div class="demo-content">
        <div class="router-simulator">
          <div class="router-header">
            <h4>路由模拟器</h4>
            <div class="route-indicator">当前路径: <strong>{{ currentPath }}</strong></div>
          </div>
          
          <div class="router-nav">
            <button @click="navigateTo('/home')" :class="['nav-btn', { active: currentPath === '/home' }]">首页</button>
            <button @click="navigateTo('/about')" :class="['nav-btn', { active: currentPath === '/about' }]">关于</button>
            <button @click="navigateTo('/contact')" :class="['nav-btn', { active: currentPath === '/contact' }]">联系我们</button>
          </div>
          
          <div class="router-view">
            <div v-if="currentPath === '/home'" class="route-component">
              <h5>首页</h5>
              <p>欢迎来到首页！这是使用 Vue Router 渲染的组件。</p>
              <p>在实际应用中，每个路由会对应一个组件，Vue Router 会负责渲染正确的组件。</p>
            </div>
            
            <div v-else-if="currentPath === '/about'" class="route-component">
              <h5>关于我们</h5>
              <p>这是关于我们页面。Vue Router 让单页面应用的页面切换变得简单高效。</p>
              <p>无需刷新整个页面，只需更新页面的部分内容。</p>
            </div>
            
            <div v-else-if="currentPath === '/contact'" class="route-component">
              <h5>联系我们</h5>
              <p>这是联系我们页面。</p>
              <p>您可以通过以下方式联系我们：</p>
              <ul>
                <li>电子邮件: contact@example.com</li>
                <li>电话: 123-456-7890</li>
                <li>地址: 示例路123号</li>
              </ul>
            </div>
          </div>
          
          <div class="router-history">
            <h6>历史记录</h6>
            <div class="history-list">
              <div v-for="(path, index) in navigationHistory" :key="index" class="history-item">
                {{ path }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 2. 动态路由参数 -->
    <section class="demo-section">
      <h3>2. 动态路由参数</h3>
      <div class="demo-content">
        <div class="dynamic-routes">
          <h4>用户详情</h4>
          
          <div class="user-selection">
            <p>选择用户查看详情:</p>
            <div class="user-buttons">
              <button 
                v-for="user in users" 
                :key="user.id"
                @click="viewUserDetail(user.id)"
                class="user-btn"
              >
                用户 {{ user.id }}
              </button>
            </div>
            
            <div class="custom-user">
              <p>或输入用户ID:</p>
              <div class="input-group">
                <input 
                  v-model="customUserId" 
                  type="number" 
                  placeholder="用户ID"
                  class="input"
                >
                <button @click="viewCustomUser" class="btn">查看</button>
              </div>
            </div>
          </div>
          
          <div class="user-detail" v-if="selectedUserId">
            <h5>用户详情 (ID: {{ selectedUserId }})</h5>
            <div v-if="currentUser" class="user-info">
              <p><strong>用户名:</strong> {{ currentUser?.name || '未登录' }}</p>
              <p><strong>邮箱:</strong> {{ currentUser.email }}</p>
              <p><strong>角色:</strong> {{ currentUser.role }}</p>
            </div>
            <div v-else class="user-not-found">
              用户不存在
            </div>
            <div class="route-info">
              <p><strong>动态路由路径:</strong> /user/{{ selectedUserId }}</p>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 3. 嵌套路由 -->
    <section class="demo-section">
      <h3>3. 嵌套路由</h3>
      <div class="demo-content">
        <div class="nested-routes">
          <h4>仪表盘 (嵌套路由示例)</h4>
          
          <div class="dashboard-layout">
            <div class="dashboard-sidebar">
              <button @click="navigateToDashboard('overview')" :class="['sidebar-btn', { active: dashboardSection === 'overview' }]">
                概览
              </button>
              <button @click="navigateToDashboard('stats')" :class="['sidebar-btn', { active: dashboardSection === 'stats' }]">
                统计数据
              </button>
              <button @click="navigateToDashboard('settings')" :class="['sidebar-btn', { active: dashboardSection === 'settings' }]">
                设置
              </button>
            </div>
            
            <div class="dashboard-content">
              <div v-if="dashboardSection === 'overview'" class="dashboard-section">
                <h5>概览</h5>
                <p>这是仪表盘的概览部分。</p>
                <div class="stats-cards">
                  <div class="stat-card">
                    <div class="stat-title">总访问量</div>
                    <div class="stat-value">1,258</div>
                  </div>
                  <div class="stat-card">
                    <div class="stat-title">活跃用户</div>
                    <div class="stat-value">42</div>
                  </div>
                  <div class="stat-card">
                    <div class="stat-title">转化率</div>
                    <div class="stat-value">12.5%</div>
                  </div>
                </div>
              </div>
              
              <div v-else-if="dashboardSection === 'stats'" class="dashboard-section">
                <h5>统计数据</h5>
                <p>这是详细的统计数据部分。</p>
                <div class="chart-placeholder">
                  [ 图表占位区 ]
                </div>
                <div class="stats-list">
                  <div class="stat-item">日访问量: 328</div>
                  <div class="stat-item">平均停留时间: 3m 45s</div>
                  <div class="stat-item">跳出率: 42.1%</div>
                </div>
              </div>
              
              <div v-else-if="dashboardSection === 'settings'" class="dashboard-section">
                <h5>设置</h5>
                <p>这是仪表盘的设置部分。</p>
                <div class="settings-form">
                  <div class="form-item">
                    <label>主题:</label>
                    <select class="select">
                      <option>浅色</option>
                      <option>深色</option>
                    </select>
                  </div>
                  <div class="form-item">
                    <label>显示数据:</label>
                    <input type="checkbox"> 显示访问量
                  </div>
                  <div class="form-item">
                    <label>自动刷新:</label>
                    <input type="checkbox"> 启用
                  </div>
                  <button class="btn">保存设置</button>
                </div>
              </div>
            </div>
          </div>
          
          <div class="route-info">
            <p><strong>嵌套路由路径:</strong> /dashboard/{{ dashboardSection }}</p>
          </div>
        </div>
      </div>
    </section>

    <!-- 4. 编程式导航 -->
    <section class="demo-section">
      <h3>4. 编程式导航</h3>
      <div class="demo-content">
        <div class="programmatic-nav">
          <h4>编程式导航演示</h4>
          
          <div class="nav-actions">
            <div class="action-group">
              <h5>基本导航</h5>
              <button @click="goToHome" class="btn">前往首页</button>
              <button @click="goToAbout" class="btn">前往关于</button>
              <button @click="goToContact" class="btn">前往联系我们</button>
            </div>
            
            <div class="action-group">
              <h5>带参数导航</h5>
              <div class="input-group">
                <input v-model="navigateUserId" type="number" placeholder="用户ID" class="input">
                <button @click="goToUser" class="btn">查看用户</button>
              </div>
            </div>
            
            <div class="action-group">
              <h5>导航方法</h5>
              <button @click="replaceRoute" class="btn">替换当前路由</button>
              <button @click="goBack" class="btn" :disabled="!canGoBack">后退</button>
              <button @click="goForward" class="btn" :disabled="!canGoForward">前进</button>
            </div>
          </div>
          
          <div class="navigation-log">
            <h5>导航日志</h5>
            <div class="log-list">
              <div v-for="(log, index) in navigationLogs" :key="index" class="log-item">
                {{ log }}
              </div>
              <div v-if="navigationLogs.length === 0" class="no-logs">
                暂无导航记录
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 5. 路由守卫和元信息 -->
    <section class="demo-section">
      <h3>5. 路由守卫和元信息</h3>
      <div class="demo-content">
        <div class="route-guards">
          <h4>路由守卫演示</h4>
          
          <div class="auth-demo">
            <h5>权限控制演示</h5>
            
            <div class="auth-status">
              <p>登录状态: <span :class="['status-badge', isAuthenticated ? 'authenticated' : 'not-authenticated']">
                {{ isAuthenticated ? '已登录' : '未登录' }}
              </span></p>
            </div>
            
            <div class="auth-actions">
              <button v-if="!isAuthenticated" @click="login" class="btn">登录</button>
              <button v-else @click="logout" class="btn btn-danger">登出</button>
            </div>
            
            <div class="protected-routes">
              <h6>受保护的路由:</h6>
              <button @click="tryAccessAdmin" class="btn btn-small">管理面板</button>
              <button @click="tryAccessProfile" class="btn btn-small">用户资料</button>
              <button @click="tryAccessSettings" class="btn btn-small">账户设置</button>
            </div>
            
            <div class="guard-log">
              <h6>守卫日志:</h6>
              <div class="log-list">
                <div v-for="(log, index) in guardLogs" :key="index" class="log-item">
                  {{ log }}
                </div>
              </div>
            </div>
          </div>
          
          <div class="meta-info">
            <h5>路由元信息</h5>
            <p>路由元信息用于存储路由相关的元数据，例如页面标题、权限要求等。</p>
            
            <div class="meta-examples">
              <div class="meta-item">
                <strong>首页:</strong>
                <CodeBlock code="{ requiresAuth: false, title: '首页', breadcrumb: '首页' }" language="javascript"></CodeBlock>
              </div>
              <div class="meta-item">
                <strong>管理面板:</strong>
                <CodeBlock code="{ requiresAuth: true, requiresAdmin: true, title: '管理面板' }" language="javascript"></CodeBlock>
              </div>
              <div class="meta-item">
                <strong>用户资料:</strong>
                <CodeBlock code="{ requiresAuth: true, title: '用户资料' }" language="javascript"></CodeBlock>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import CodeBlock from '@components/CodeBlock.vue'

// 1. 基础路由演示
const currentPath = ref('/home')
const navigationHistory = ref(['/home'])

const navigateTo = (path) => {
  currentPath.value = path
  navigationHistory.value.push(path)
  // 限制历史记录长度
  if (navigationHistory.value.length > 10) {
    navigationHistory.value.shift()
  }
}

// 2. 动态路由参数
const users = ref([
  { id: 1, name: '张三', email: 'zhangsan@example.com', role: '管理员' },
  { id: 2, name: '李四', email: 'lisi@example.com', role: '用户' },
  { id: 3, name: '王五', email: 'wangwu@example.com', role: '用户' },
  { id: 4, name: '赵六', email: 'zhaoliu@example.com', role: '访客' }
])

const selectedUserId = ref(null)
const customUserId = ref('')

const currentUser = computed(() => {
  if (!selectedUserId.value) return null
  return users.value.find(user => user.id === Number(selectedUserId.value)) || null
})

const viewUserDetail = (userId) => {
  selectedUserId.value = userId
}

const viewCustomUser = () => {
  if (customUserId.value) {
    selectedUserId.value = Number(customUserId.value)
  }
}

// 3. 嵌套路由
const dashboardSection = ref('overview')

const navigateToDashboard = (section) => {
  dashboardSection.value = section
}

// 4. 编程式导航
const navigateUserId = ref('')
const navigationLogs = ref([])
const historyPosition = ref(0)

const canGoBack = computed(() => historyPosition.value > 0)
const canGoForward = computed(() => historyPosition.value < navigationLogs.value.length - 1)

const addNavigationLog = (message) => {
  // 如果在历史记录中间，清除前进记录
  if (historyPosition.value < navigationLogs.value.length - 1) {
    navigationLogs.value = navigationLogs.value.slice(0, historyPosition.value + 1)
  }
  
  navigationLogs.value.push(`${new Date().toLocaleTimeString()}: ${message}`)
  historyPosition.value = navigationLogs.value.length - 1
  
  // 限制日志长度
  if (navigationLogs.value.length > 10) {
    navigationLogs.value.shift()
    historyPosition.value--
  }
}

const goToHome = () => {
  addNavigationLog('编程式导航到 /home')
}

const goToAbout = () => {
  addNavigationLog('编程式导航到 /about')
}

const goToContact = () => {
  addNavigationLog('编程式导航到 /contact')
}

const goToUser = () => {
  if (navigateUserId.value) {
    addNavigationLog(`编程式导航到 /user/${navigateUserId.value}`)
  }
}

const replaceRoute = () => {
  addNavigationLog('替换当前路由到 /about')
}

const goBack = () => {
  if (canGoBack.value) {
    historyPosition.value--
    addNavigationLog('返回上一页')
  }
}

const goForward = () => {
  if (canGoForward.value) {
    historyPosition.value++
    addNavigationLog('前进到下一页')
  }
}

// 5. 路由守卫和元信息
const isAuthenticated = ref(false)
const guardLogs = ref([])

const addGuardLog = (message) => {
  guardLogs.value.push(`${new Date().toLocaleTimeString()}: ${message}`)
  // 限制日志长度
  if (guardLogs.value.length > 10) {
    guardLogs.value.shift()
  }
}

const login = () => {
  isAuthenticated.value = true
  addGuardLog('用户登录成功')
}

const logout = () => {
  isAuthenticated.value = false
  addGuardLog('用户登出')
}

const tryAccessAdmin = () => {
  if (!isAuthenticated.value) {
    addGuardLog('路由守卫: 未登录，无法访问管理面板')
    return
  }
  
  // 模拟管理员检查
  const isAdmin = true
  if (!isAdmin) {
    addGuardLog('路由守卫: 权限不足，需要管理员权限')
    return
  }
  
  addGuardLog('路由守卫: 验证通过，允许访问管理面板')
}

const tryAccessProfile = () => {
  if (!isAuthenticated.value) {
    addGuardLog('路由守卫: 未登录，重定向到登录页')
    return
  }
  
  addGuardLog('路由守卫: 验证通过，允许访问用户资料')
}

const tryAccessSettings = () => {
  if (!isAuthenticated.value) {
    addGuardLog('路由守卫: 未登录，重定向到登录页')
    return
  }
  
  addGuardLog('路由守卫: 验证通过，允许访问账户设置')
}
</script>

<style scoped>
.vue-router-demo {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

h2 {
  color: #333;
  margin-bottom: 30px;
  text-align: center;
}

.introduction {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
}

.demo-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 30px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h3 {
  color: #42b983;
  margin-bottom: 20px;
  border-bottom: 2px solid #42b983;
  padding-bottom: 10px;
}

.demo-content {
  margin-bottom: 20px;
}

.btn {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s;
}

.btn:hover:not(:disabled) {
  background-color: #3aa876;
}

.btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.btn-small {
  padding: 6px 12px;
  font-size: 12px;
}

.btn-danger {
  background-color: #dc3545;
}

.btn-danger:hover:not(:disabled) {
  background-color: #c82333;
}

.input {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 6px;
  flex: 1;
}

.select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 6px;
}

.input-group {
  display: flex;
  gap: 10px;
  margin-bottom: 10px;
}

/* 路由模拟器样式 */
.router-simulator {
  background-color: #f8f9fa;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #ddd;
}

.router-header {
  background-color: #42b983;
  color: white;
  padding: 15px;
}

.router-header h4 {
  margin: 0 0 10px 0;
}

.route-indicator {
  font-size: 14px;
  opacity: 0.9;
}

.router-nav {
  display: flex;
  background-color: #f0f0f0;
  border-bottom: 1px solid #ddd;
}

.nav-btn {
  padding: 12px 20px;
  border: none;
  background-color: transparent;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.nav-btn:hover {
  background-color: #e0e0e0;
}

.nav-btn.active {
  background-color: #42b983;
  color: white;
}

.router-view {
  min-height: 200px;
  padding: 20px;
  background-color: white;
}

.route-component {
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.router-history {
  padding: 15px;
  background-color: #f8f9fa;
  border-top: 1px solid #ddd;
}

.router-history h6 {
  margin: 0 0 10px 0;
}

.history-list {
  max-height: 100px;
  overflow-y: auto;
  font-size: 12px;
}

.history-item {
  padding: 4px 0;
  color: #666;
}

/* 动态路由样式 */
.dynamic-routes {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.user-selection {
  margin-bottom: 20px;
}

.user-buttons {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.user-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.user-btn:hover {
  background-color: #42b983;
  color: white;
  border-color: #42b983;
}

.custom-user {
  margin-bottom: 20px;
}

.user-detail {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 15px;
}

.user-info p {
  margin: 10px 0;
}

.user-not-found {
  color: #dc3545;
  font-style: italic;
}

.route-info {
  background-color: #e3f2fd;
  padding: 10px;
  border-radius: 6px;
  font-size: 14px;
}

/* 嵌套路由样式 */
.nested-routes {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.dashboard-layout {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.dashboard-sidebar {
  min-width: 150px;
  background-color: #2c3e50;
  border-radius: 8px;
  padding: 10px;
}

.sidebar-btn {
  width: 100%;
  padding: 12px;
  margin-bottom: 10px;
  border: none;
  background-color: transparent;
  color: rgba(255, 255, 255, 0.7);
  text-align: left;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.sidebar-btn:hover {
  background-color: rgba(255, 255, 255, 0.1);
  color: white;
}

.sidebar-btn.active {
  background-color: #42b983;
  color: white;
}

.dashboard-content {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
}

.dashboard-section {
  padding: 20px;
}

.stats-cards {
  display: flex;
  gap: 15px;
  margin-top: 20px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 120px;
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 8px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #42b983;
}

.chart-placeholder {
  height: 200px;
  background-color: #f8f9fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  margin-bottom: 20px;
}

.stats-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-item {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
}

.settings-form {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 编程式导航样式 */
.programmatic-nav {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.nav-actions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.action-group h5 {
  margin: 0 0 10px 0;
}

.action-group button {
  margin-bottom: 10px;
  width: 100%;
}

.navigation-log {
  background-color: white;
  padding: 15px;
  border-radius: 8px;
}

.navigation-log h5 {
  margin: 0 0 10px 0;
}

.log-list {
  max-height: 200px;
  overflow-y: auto;
  font-size: 14px;
}

.log-item {
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.log-item:last-child {
  border-bottom: none;
}

.no-logs {
  color: #999;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

/* 路由守卫样式 */
.route-guards {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
}

.auth-demo {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.auth-status {
  margin-bottom: 15px;
}

.status-badge {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.status-badge.authenticated {
  background-color: #d4edda;
  color: #155724;
}

.status-badge.not-authenticated {
  background-color: #f8d7da;
  color: #721c24;
}

.auth-actions {
  margin-bottom: 20px;
}

.protected-routes {
  margin-bottom: 20px;
}

.protected-routes h6 {
  margin: 0 0 10px 0;
}

.protected-routes .btn {
  margin-right: 10px;
  margin-bottom: 10px;
}

.guard-log h6 {
  margin: 0 0 10px 0;
}

.meta-info {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
}

.meta-examples {
  margin-top: 15px;
}

.meta-item {
  margin-bottom: 10px;
}

.meta-item pre {
  background-color: #f8f9fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  overflow-x: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard-layout {
    flex-direction: column;
  }
  
  .dashboard-sidebar {
    display: flex;
    overflow-x: auto;
    min-width: auto;
  }
  
  .sidebar-btn {
    white-space: nowrap;
    margin-right: 10px;
    margin-bottom: 0;
  }
  
  .nav-actions {
    grid-template-columns: 1fr;
  }
  
  .stats-cards {
    flex-direction: column;
  }
  
  .input-group {
    flex-direction: column;
  }
}
</style>